package base2dev.web.common;

import javax.persistence.EntityManager;
import javax.persistence.EntityManagerFactory;
import javax.transaction.TransactionManager;

import org.apache.wicket.Page;
import org.apache.wicket.Response;
import org.apache.wicket.injection.web.InjectorHolder;
import org.apache.wicket.protocol.http.WebApplication;
import org.apache.wicket.protocol.http.WebRequest;
import org.apache.wicket.spring.injection.annot.SpringBean;

public class WebRequestCycle extends
		org.apache.wicket.protocol.http.WebRequestCycle {

	
	private TransactionManager tm;
	
	
//	@SpringBean
//	private JpaTransactionManager transactionManager;
//
//	public void setTransactionManager(JpaTransactionManager transactionManager) {
//		this.transactionManager = transactionManager;
//	}
//
//	
//	private DefaultTransactionDefinition def;
	
	@SpringBean
	private EntityManagerFactory entityManagerFactory;

	public void setEntityManagerFactory(
			EntityManagerFactory entityManagerFactory) {
		this.entityManagerFactory = entityManagerFactory;
	}

	private EntityManager em;

	public WebRequestCycle(WebApplication application, WebRequest request,
			Response response) {
		super(application, request, response);
		InjectorHolder.getInjector().inject(this);

		em = entityManagerFactory.createEntityManager();
		
		
//		DefaultTransactionDefinition def = new DefaultTransactionDefinition();
//		def.setPropagationBehavior(Propagation.REQUIRED);

	}

	@Override
	protected void onBeginRequest() {
		super.onBeginRequest();
		 em.getTransaction().begin();
	  
	  
	}

	@Override
	protected void onEndRequest() {
		super.onEndRequest();
		 em.getTransaction().commit();
//		try {
//			transactionManager.commit();
//		} catch (SecurityException e) {
//			// TODO Auto-generated catch block
//			e.printStackTrace();
//		} catch (IllegalStateException e) {
//			// TODO Auto-generated catch block
//			e.printStackTrace();
//		} catch (RollbackException e) {
//			// TODO Auto-generated catch block
//			e.printStackTrace();
//		} catch (HeuristicMixedException e) {
//			// TODO Auto-generated catch block
//			e.printStackTrace();
//		} catch (HeuristicRollbackException e) {
//			// TODO Auto-generated catch block
//			e.printStackTrace();
//		} catch (SystemException e) {
//			// TODO Auto-generated catch block
//			e.printStackTrace();
//		}
	}

	@Override
	public Page onRuntimeException(Page page, RuntimeException e) {
		 em.getTransaction().rollback();

//		try {
//			transactionManager.rollback();
//		} catch (IllegalStateException e1) {
//			// TODO Auto-generated catch block
//			e1.printStackTrace();
//		} catch (SecurityException e1) {
//			// TODO Auto-generated catch block
//			e1.printStackTrace();
//		} catch (SystemException e1) {
//			// TODO Auto-generated catch block
//			e1.printStackTrace();
//		}
		return super.onRuntimeException(page, e);
	}
}
